/**
 * 函数式组件
 */
import React, {useState, useEffect} from "react";
import axios from 'axios'
import {Button, ConfigProvider, Form, Input, Layout, Table, message, Modal} from 'antd';
import zhCN from "antd/es/locale/zh_CN";
import servicePath from "../config/apiConfig";
import '../assets/css/home.css'
import AddStudentFun from "../components/AddStudentFun";
import UpdateStudentFun from "../components/UpdateStudentFun";
const { Header, Content } = Layout
const { confirm } = Modal;
const newStudentList = []
for(let i=11; i<=30; i++) {
    newStudentList.push({
        id: i,
        snumber: '2010500'+i,
        name: '小红',
        classes: '计算机2班',
        sex: '女',
        cscore: 95,
        jscore: 87,
        dbscore: 88
    })
}

function HomeFun() {

    const [snumber, setSnumber] = useState('')
    const [name, setName] = useState('')
    const [studentList, setStudentList] = useState([])
    const [pagination, setPagination] = useState({
        currentPage: 1,
        pageSize: 2,
        total: 0,
    })
    const [loading, setLoading] = useState(false)
    const [showAdd, setShowAdd] = useState(false)
    const [showUpdate, setShowUpdate] = useState(false)
    const [studentId, setStudentId] = useState('')
    const [studentInfo, setStudentInfo] = useState({})
    const [isSearch, setIsSearch] = useState(false)

    // 初始化表格列
    const columns = [
        {
            title: '学号',
            dataIndex: 'snumber',
        },
        {
            title: '姓名',
            dataIndex: 'name',
        },
        {
            title: '班级',
            dataIndex: 'classes',
        },
        {
            title: '性别',
            dataIndex: 'sex',
        },
        {
            title: 'c语言成绩',
            dataIndex: 'cscore',
        },
        {
            title: 'java语言成绩',
            dataIndex: 'jscore',
        },
        {
            title: '数据库语言成绩',
            dataIndex: 'dbscore',
        },
        {
            title: '操作',
            width: '20%',
            render: (student) => (
                <>
                    <Button type="primary" size="middle" className="table-btn table-update-btn" onClick={()=>updateStudent(student)}>修改</Button>
                    <Button type="danger" size="middle" className="table-btn" onClick={()=>deleteStudent(student)}>删除</Button>
                </>
            ),
        }
    ];

    // 搜索
    const getSearchListByName = (name, currentPage, pageSize)=>{
        axios({
            method: 'get',
            url: servicePath.findByName,
            params: {name, currentPage, pageSize},
        }).then(res=>{
            let data = res.data
            if(data.code === 200) {
                setStudentList(data.msg.data)
                setPagination({
                    currentPage: currentPage,
                    pageSize: pageSize,
                    total: data.msg.total
                })
            }
        })
    }
    const getSearchListBySnumber = (snumber, currentPage, pageSize)=>{
        axios(servicePath.findBySnumber+snumber).then(res=>{
            let data = res.data
            if(data.code === 200) {
                setStudentList(data.msg.data)
                setPagination({
                    currentPage: currentPage,
                    pageSize: pageSize,
                    total: data.msg.total
                })
            }
        })
    }
    const search = ()=>{
        setIsSearch(true);
        if(snumber.trim()) {
            getSearchListBySnumber(snumber.trim(), 1, pagination.pageSize);
        } else if(name.trim()) {
            getSearchListByName(name.trim(), 1, pagination.pageSize)
        }
    }
    // 重置
    const resetForm =()=>{
        setIsSearch(false);
        setSnumber('')
        setName('')
        getStudentList(1, pagination.pageSize);
    }
    // 录入学生信息
    const addStudent =()=>{
        setShowAdd(true)
    }
    // 更新学生信息
    const updateStudent = (student)=>{
        // console.log('更新学生信息', student)
        setShowUpdate(true)
        setStudentId(student.id)
        setStudentInfo(student)
    }
    // 删除学生信息
    const deleteStudent = (student)=>{
        confirm({
            title: '确定要删除此条记录吗?',
            content: '如果你点击确定按钮，该记录将会永远被删除，无法恢复',
            onOk() {
                axios({
                    method: 'delete',
                    url: servicePath.deleteStudent + student.id
                }).then(res=>{
                    const data = res.data
                    if(data.code===200) {
                        message.success('删除学生信息成功！',1);
                        if((pagination.currentPage-1)*pagination.pageSize===pagination.total-1) {
                            let current = pagination.currentPage>1 ? pagination.currentPage-1 : 1
                            getStudentList(current, pagination.pageSize)
                        } else {
                            getStudentList(pagination.currentPage, pagination.pageSize)
                        }
                    } else {
                        message.error('删除学生信息失败！',1);
                    }
                })
            },
            onCancel() {
                message.info('取消删除！',1);
            },
        });

    }
    // 导出成绩
    const download =()=>{
        console.log('导出学生成绩')
        axios(servicePath.exportToExcel, { responseType: 'blob' }).then(res => {
            console.log(res)
            // const blob = new Blob([res.data], {
            //   type: 'application/octet-stream;charset=utf-8'
            // })
            const blob = new Blob([res.data], {
                type: 'application/vnd.ms-excel;charset=utf-8'
            })
            const url = window.URL.createObjectURL(blob)
            const link = document.createElement('a')
            link.href = url
            link.download = `学生成绩单_${decodeURI(
                res.headers['content-disposition'].split('_')[1]
            )}`
            // console.log(res.headers['content-disposition'])
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
        }).catch(function (error) {
            console.log(error)
        })
    }
    // 关闭添加对话框
    const closeAddModal = ()=>{
        if(isSearch) {
            resetForm();
        } else {
            getStudentList(1, pagination.pageSize);
        }
        setShowAdd(false)
    }
    // 关闭更新对话框
    const closeUpdateModal = ()=>{
        if(isSearch) {
            if(name.trim()) {
                getSearchListByName(name.trim(), pagination.currentPage, pagination.pageSize)
            } else {
                getSearchListBySnumber(snumber.trim(), pagination.currentPage, pagination.pageSize);
            }
        } else {
            getStudentList(pagination.currentPage, pagination.pageSize)
        }
        setShowUpdate(false)
        setStudentId('')
        setStudentInfo({})
    }

    // 分页器配置
    const paginationProps = {
        position: 'bottom-center',
        showSizeChanger: true, //设置每页显示数据条数
        showQuickJumper: true,
        showTotal: () => `共${pagination.total}条`,
        current: pagination.currentPage,
        pageSize: pagination.pageSize,
        pageSizeOptions: [1,2,5,10,20,40],
        total: pagination.total,  //数据的总的条数
        onChange: (current, pageSize) => changePage(current, pageSize), // 点击当前页码
        onShowSizeChange: (current, pageSize) => { //设置每页显示数据条数，current表示当前页码，pageSize表示每页展示数据条数
            changePage(current, pageSize)
        }
    }

    // 改变当前页码或每页多少条
    const changePage = (currentPage, pageSize)=>{
        // console.log(currentPage, pageSize)
        // let total = pagination.total
        // setPagination({
        //     currentPage, pageSize, total
        // })
        if(isSearch) {
            if(name.trim()) {
                getSearchListByName(name.trim(), currentPage, pageSize)
            } else {
                getSearchListBySnumber(snumber.trim(), currentPage, pageSize);
            }
        } else {
            getStudentList(currentPage, pageSize)
        }
    }

    // 获取学生信息列表
    const getStudentList = (currentPage, pageSize)=>{
        axios({
            method: 'get',
            url: servicePath.getStudentList,
            params: {currentPage, pageSize},
        }).then(res=>{
            let data = res.data
            if(data.code === 200) {
                setStudentList(data.msg.data)
                setPagination({
                    currentPage: currentPage,
                    pageSize: pageSize,
                    total: data.msg.total
                })
            }
        })
    }


    useEffect(()=>{
        // setStudentList(newStudentList)
        // console.log(studentList)
        getStudentList(pagination.currentPage, pagination.pageSize)
    }, [])


    return (
        <div className="home-container">
            <Layout className="layout">
                <Header className="layout-header">
                    简易学生成绩管理系统
                </Header>

                <Form name="horizontal_search" layout="inline" className="layout-search">
                    <Form.Item label="学号">
                        <Input placeholder="精确匹配" value={snumber} size="small" onChange={(e)=>{setSnumber(e.target.value)}}/>
                    </Form.Item>
                    <Form.Item label="姓名">
                        <Input placeholder="模糊匹配" value={name} size="small" onChange={(e)=>{setName(e.target.value)}}/>
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" size="small" className="form-btn" onClick={search}>查询</Button>
                        <Button type="default" size="small" className="form-btn reset-btn" onClick={resetForm}>重置</Button>
                        <Button type="default" size="small" className="form-btn add-btn" onClick={addStudent}>录入</Button>
                        <Button type="dashed" size="small" className="form-btn" onClick={download}>导出成绩</Button>
                    </Form.Item>
                </Form>

                <Content className="layout-Content">
                    <ConfigProvider locale={zhCN}>
                        <Table bordered columns={columns} dataSource={studentList} scroll={{ y: 400 }}
                               rowKey={record => record.snumber} loading={loading} pagination={paginationProps} />
                    </ConfigProvider>

                </Content>
            </Layout>

            {
                showAdd ? (<AddStudentFun isVisible={showAdd} closeModal={closeAddModal}/>) : null
            }
            {
                showUpdate ? (<UpdateStudentFun isVisible={showUpdate} closeModal={closeUpdateModal} studentId={studentId} studentInfo={studentInfo}/>) : null
            }
        </div>
    )
}

export default HomeFun
